﻿Public Class RoleForm
    Private parentForm As SearchRolesForm = New SearchRolesForm

    Enum state
        insert
        edit
    End Enum

    Dim action As state = state.insert

    Public Sub New()
        InitializeComponent()
    End Sub

    Public Sub New(ByRef parentFormParam As SearchRolesForm)
        InitializeComponent()
        parentForm = parentFormParam
    End Sub
    Private Sub RoleForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        Dim role As Role = Nothing

        If Me.validateRequiredFields() Then
            If Me.action = state.insert Then
                If Me.validateDupicateRole = True Then
                    role = New Role(Nothing, txtName.Text, rtxtDescription.Text)
                    GenericAdministrator.insert(role)
                    Me.Close()
                    Dim searchRoleForm As New SearchRolesForm()
                    searchRoleForm.Show()
                End If

            Else
                role = New Role(parentForm.idSelect, Me.txtName.Text, Me.rtxtDescription.Text)
                GenericAdministrator.update(role)
                Me.Close()
                Dim searchRoleForm As New SearchRolesForm()
                searchRoleForm.Show()
            End If
        End If
    End Sub

    Private Function validateDupicateRole()
        Dim role As New Role(Nothing, txtName.Text, Nothing)
        Dim table As Data.DataTable = GenericAdministrator.searchDataByFilter(role)

        If table.Rows.Count > 0 Then
            MsgBox("El rol ya Existe en la base de Datos.", vbCritical, "Importante")
            Return False
        End If

        Return True
    End Function

    Private Function validateRequiredFields()
        If Me.txtName.Text = "" Then
            MsgBox("Nombre es Requerido", vbCritical, "Importante")
            Me.txtName.Focus()
            Return False
        End If

        If Me.rtxtDescription.Text = "" Then
            MsgBox("Descripcion es Requerida", vbCritical, "Importante")
            Me.rtxtDescription.Focus()
            Return False
        End If

        Return True

    End Function

    Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        Me.Close()
    End Sub
End Class